package com.sunnada.wfs.geoserverRest;

import com.sunnada.wfs.DatabaseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GerServerService {

    @Value("${geoserver.workspace}")
    private String workspace;

    @Value("${geoserver.datastore}")
    private String datastore;

    @Autowired
    private DatabaseInfo databaseInfo;

    @Autowired
    private GeoServerRest geoServerRest;

    public boolean deploy(String featureType) throws IOException {
        // 检测工作空间是否存在，若不存在则创建工作空间，若存在则进入下一步
        if (!geoServerRest.haveWorksapce(workspace)) geoServerRest.createWorksapce(createWorkspaceBodyXml());
        // 检测数据源是否存在，若不存在则创建数据源，若存在则进行下一步
        if (!geoServerRest.haveDatastore(workspace,datastore)) geoServerRest.createDatastore(workspace,createDataStoreBodyXml());
        // 校验图层是否已发布，已发布则返回false表示发布失败，若未发布则发布图层
        if (!geoServerRest.haveFeatureType(workspace,datastore,featureType)) {
            geoServerRest.publicTableFromPostGis(workspace,datastore,featureType);
            return true;
        }else {
            return false;
        }
    }


    private String createDataStoreBodyXml(){
        String dataStoreBody = "<dataStore><name>%s</name><connectionParameters><host>%s</host><port>%s</port><database>%s</database><user>%s</user><passwd>%s</passwd><dbtype>%s</dbtype></connectionParameters></dataStore>";
        dataStoreBody = String.format(dataStoreBody,datastore,databaseInfo.getHost(),databaseInfo.getPort(),databaseInfo.getDatabase(),databaseInfo.getUser(),databaseInfo.getPasswd(),databaseInfo.getDbtype());
        return dataStoreBody;
    }

    private String createWorkspaceBodyXml(){
        String workspaceBody = "<workspace><name>%s</name></workspace>";
        workspaceBody = String.format(workspaceBody,workspace);
        return workspaceBody;
    }
}
